<?php
namespace app\api\controller;

use app\common\lib\AliSms;
use app\common\model\SmsCodeModel;
use app\middleware\Auth;

class Sms extends Common
{
    protected $middleware = [Auth::class];

    /**
     * 短信验证码
     * @author 贺强
     * @time   2022/5/23 16:21
     */
    public function send_sms_code()
    {
        $param = $this->param;
        $mobile = $param['mobile'] ?? '';
        if (empty($mobile)) {
            return ajax('手机号不能为空', 101);
        }
        if (!is_mobile($mobile)) {
            return ajax('手机号不合法', 301);
        }
        SmsCodeModel::delByWhere(['mobile' => $mobile]);
        $code = get_random_num();
        $data = compact('mobile', 'code');
        $res = SmsCodeModel::add($data);
        if (!$res) {
            return ajax('创建失败', 400);
        }
        $flag = AliSms::sendVerifyCode($mobile, $code);
        if (!$flag) {
            return ajax('短信发送失败', 302);
        }
        return ajax('发送成功');
    }
}
